// packagBuy/pages/found/contentDetail/contentDetail.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import {
  foundApi,
  QRCode,
  centerCount,
  getParamByScene
} from '../../../../config/config'
const getURL = require('../../../../utils/util') //引入配置接口文件
var configUrl = require('../../../../config/config') //引入配置接口文件
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    contentId: '',
    detailData: {
      // name:'《家居攻略》家居保养小细节,学会你就是朋友圈家居达人',
      // contentDesc:'本套样板间为公司标准样板间，定制系列为纯璞东方成品系列为纯璞东方+挪威森林'
    },
    userInfo: '', //用户信息
    canvasHeight: 500, // canvas高度
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    screenWidth: wx.getSystemInfoSync().windowWidth,
    statusHeight: app.globalData.StatusBar,
    headerOpacity: 0, // 头部背景透明度
    headerClass: '', // 头部样式
    swiperList: [
      // {type:'类型：image/video',picUrl:'图片地址',url:'视频地址',imgUrl:'视频封面图'}
      // {type:'image',picUrl:'/group1/M00/00/E7/rB8Mkl9lcB2AVfhMAAB35o_v8dw857.jpg'}
    ],
    swiperIndex: 0, //轮播索引
    swiperTyle: false,
    PlayTyle: false,
    showNotWifiPaly: false, // 是否wify播放视频
    shareModal: true,
    contentInfo: '', //内容详情
    thumbsUpNum: 0, //点赞数量
    seeNum: 0, //查看数量
    isCollection: false, //是否已收藏
    collectionId: '', //收藏记录ID
    isThumbsUp: false, //是否已点赞
    thumbsUpId: '', //点赞记录ID
    modelPopup: '', // 弹窗类型：shear-pop-download 分享海报 ， goods-pop 相关商品 , comment-pop 评论
    goodsList: [], // 相关商品列表,
    commentList: [
      // {
      //   id:1,
      //   userName:'曾曾',
      //   icon:'https://thirdwx.qlogo.cn/mmopen/vi_32/egBYb3IdwdjZia4wYr5K3E5W1RVkibpbstPiaqcP4cLn48LyUvLju899cMLdIic1hb9mOmPoyXv4vdLAqkViaBPS0eA/132',
      //   createTime:'2020/09/20',
      //   content:'沙发真好。简欧风格，又简单又时尚又省地，虽然我们家户型大，但也不能浪费地方呀。这款沙发是大小户型通用呀。',
      //   thumbsUpNumber:2324,//点赞数
      //   isThumbsUp:false,//是否已点赞
      //   thumbsUpId:'1',//点赞记录ID
      //   isOneself:true,//是否自己回复
      // }
    ], //评论列表
    commentContent: '', //发表评论的内容
    canvasAvatar: '', //分享海报头像
    canvasMainPic: '', //分享海报主图
    canvasQrCode: '', //分享海报二维码
    canvasBottomBg: '', //分享海报底部图片
    shareType: app.globalData.share, //是否分享进入
    /**-合伙人--*/
    isShowPartnerAll: 1,
    showPartnerCodePop: false,
    authorizationPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    let that = this
    if (!wx.getStorageSync('addrCode').provinceCode) {
      app.getUserLocation() //初始化获取定位地址
    }
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    if (options.scene || options.hid) {
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      if (options.hid) {
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                }
              }
              // this.setData({
              //   isShowGetUserInfo: true
              // })
            }
            app.bindingPartner(options.hid)
            this.loadFn(options)
          }
        }, 500)
      } else {
        app.getShareCode(scene, (res) => {
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
                // this.setData({
                //   isShowGetUserInfo: true
                // })
              }
              app.bindingPartner(res.userId)
              options.id = res.id
              this.loadFn(options)
            }
          }, 1000)
        })
        console.log('合伙人分享')
      }
    } else if (options.id) {
      this.loadFn(options)
    }
  },
  bindGetUserInfo: function (e) { //登录-注册
    var that=this;
    app.getUserInfo()
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
    var setFun=setInterval(()=>{
      if(wx.getStorageSync('showGetPhone')){
        that.setData({
          getPhoneNumberData:{
            isShowGetPhoneNumber:true, 
          }
        })
        wx.removeStorageSync('showGetPhone')
        clearInterval(setFun)
      }
    },1000)
    
  },
  onCloseShowGetUserInfo() { //关闭弹出层
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
   /**绑定手机号 ---str*/
   closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false

      }
    })
  },
  getPhoneNumber(e){
    var that=this;
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',configUrl.decryptGetPhone,option,(res)=>{
        if(res.data.success==1){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false,
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
        }
      }) 
    } else {
      console.log('取消')
    }
  },
  /**  end
   *  绑定手机号
   */
  loadFn(options) {
    this.setData({
      contentId: options.id
    })
    this.getUserInfo()
    this.getDetailData()
    this.getGoodsList()
    // this.getCommentList()
    this.getCanvasBtImageInfo()
    setTimeout(() => {
      this.getBannerHeight()
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    if (this.data.contentId) {
      //保存访问足迹
      app.saveAccessFootprint(this.data.footprintGuid, 'content', this.data.contentId)
    } else {
      //拿到资源id再记录足迹
      var footprintWaitResourceIdTimer = setInterval(()=>{
        if(this.data.contentId){
          //保存访问足迹
          app.saveAccessFootprint(this.data.footprintGuid, 'content', this.data.contentId)
          clearInterval(footprintWaitResourceIdTimer)
        }
      }, 100)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    return {
      title: that.data.detailData.name,
      desc: that.data.detailData.name,
      path:`/packagBuy/pages/found/contentDetail/contentDetail?id=${this.data.contentId}&hid=${wx.getStorageSync('loginMsg').userId}`
    }
  },
  getBannerHeight() {
    const query = wx.createSelectorQuery()
    query.select('#swiper').boundingClientRect()
    query.exec((res) => {
      this.setData({
        swiperHeight: res[0].height || 0
      })
    })
    const menu = wx.createSelectorQuery()
    menu.select('#contentTitle').boundingClientRect()
    menu.exec((res) => {
      this.setData({
        titleHeight: res[0].height || 0,
        titleTop: res[0].top || 0
      })
    })
  },
  // 监听滚动
  onPageScroll: function (e) {
    const fixedHeight = this.data.titleTop + this.data.titleHeight
    const swiperHeight = this.data.swiperHeight
    const scrollTop = e.scrollTop
    const topHeight = Number(this.data.statusHeight) + 44
    // const per=scrollTop/topHeight
    // const per = scrollTop/(swiperHeight-topHeight)
    const per = scrollTop / (this.data.swiperHeight - topHeight)
    if ((per >= 1 && this.data.headerOpacity < 1) || per < 1) {
      this.setData({
        headerOpacity: per > 1 ? 1 : per,
        headerClass: per > 1 ? 'font-back' : ''
      });
    }
  },

  // 获取详情数据
  getDetailData() {
    const apiUrl = `${foundApi.queryDetail}${this.data.contentId}`
    app.reqFun.requestJson('GET', apiUrl, {}, (response) => {
      if (response.data) {
        const res = response.data
        if (res.success == 1 && res.data) {
          const data = res.data
          let content = data.content
          // content=content.replace(/<section/g, '<div')
          // .replace(/\/section>/g, '\div>');
          content = content.replace(/;\s*width\s*:\s*/g, ';max-width:100%;');
          //content=content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ')
          content = content.replace(/<img[^>]*>/gi, (match, capture) => {
            return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%!important;height:auto;display:block"') // 替换style
          })
          content = content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ')

          const pictureList = data.pictureList && data.pictureList.map(v => {
            return {
              type: 'image',
              picUrl: v.picturePath
            }
          })
          this.setData({
            swiperList: pictureList,
            detailData: data,
            contentInfo: content,
            thumbsUpNum: data.thumbsUpNum || 0,
            seeNum: data.seeNum || 0,
            isThumbsUp: !!data.isThumbsUp,
            isCollection: data.isCollection,
            collectionId: data.collectionId,
            thumbsUpId: data.thumbsUpId
          })
        }
      }
    })
  },
  // 获取相关商品
  getGoodsList() {
    const apiUrl = `${foundApi.querySkuByContentId}${this.data.contentId}`
    const params = {
      provinceCode: wx.getStorageSync('addrCode').provinceCode
    }
    app.reqFun.requestForm('POST', apiUrl, params, (response) => {
      if (response.data) {
        const res = response.data
        if (res.success == 1 && res.data) {
          let goodsList = res.data
          goodsList.forEach(v => {
            v.productMainPic = getURL.getImgUrl(v.productMainPic)
            if (v.skuPic) {
              v.skuPic = getURL.getImgUrl(v.skuPic)
            }
          })

          this.setData({
            goodsList
          })
        }
      }
    })
  },
  // 获取评论
  getCommentList() {
    const apiUrl = `${foundApi.commentPage}${this.data.contentId}`
    app.reqFun.requestForm('POST', apiUrl, {}, (response) => {
      if (response.data) {
        const res = response.data
        if (res.success == 1 && res.data) {
          let goodsList = res.data
          commentList.forEach(v => {
            v.icon = getURL.getImgUrl(v.icon)
          })

          this.setData({
            commentList
          })
        }
      }
    })
  },

  // 获取个人头像与昵称
  getUserInfo() {
    const that = this
    app.reqFun.requestJson('GET', centerCount, '', (response) => {
      if (response.data) {
        const res = response.data
        if (res.success === 1 && res.data) {
          let userInfo = res.data.userInfo
          // const userIcon = getURL.getImgUrl(userInfo.icon)
          // userInfo.icon = userIcon
          let userIcon = ''
          let loginMsg = wx.getStorageSync('loginMsg')
          if(loginMsg.partner && loginMsg.partnerInfo) {
           userIcon = getURL.getImgUrl(loginMsg.partnerInfo.partnerPhoto)
           userInfo.icon = userIcon
           userInfo.nickname = loginMsg.partnerInfo.partnerNickName
           userInfo.phone = loginMsg.partnerInfo.partnerPhone
          } else {
           userIcon = getURL.getImgUrl(userInfo.icon)
           userInfo.icon = userIcon
          }
          that.setData({
            userInfo
          })
          // 获取当前头像信息，以备保存分享海报时使用
          wx.getImageInfo({
            src: userIcon,
            success: function (res) {
              that.setData({
                canvasAvatar: res.path
              })
            }
          })
        }
      }
    })
  },
  // 获取分享主图的图片信息，以备保存海报图片到手机相册时使用
  getCavasMainImage() {
    const that = this
    let mainImage = ''
    const swiperList = that.data.swiperList
    if (swiperList && swiperList.length) {
      mainImage = swiperList[0].picUrl
    }
    wx.getImageInfo({
      src: getURL.getImgUrl(mainImage),
      success: function (res) {
        that.setData({
          canvasMainPic: res.path,
          mainPicWidth: res.width,
          mainPicHeight: res.height
        })
      }
    })
  },
  // 获取分享图片底部背景图信息，以备保存分享海报时使用
  getCanvasBtImageInfo() {
    const that = this
    wx.getImageInfo({
      src: 'https://gcenterimg.quanyou.com.cn/img_source/u_found_share_bottom.png',
      success: function (res) {
        that.setData({
          canvasBottomBg: res.path
        })
      }
    })
  },
  //返回
  goreBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  //返回主页
  goHome: function (e) {
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
    app.globalData.share = false;
  },
  //获取轮播图片索引
  getSwiperPage: function (e) {
    const changeData = {
      swiperTyle: e.detail.current != 0,
      swiperIndex: e.detail.current,
    }
    if (e.detail.current != 0) {
      this.stopPalyVideo()
    } else {
      changeData.PlayTyle = false
    }
    this.setData(changeData)
  },
  //播放状态交互
  showAndHiddenImg: function (e) {
    this.setData({
      PlayTyle: e.detail.current != 0,
    })
  },
  // 查看大图
  viewBigPicture(e) {
    const src = e.currentTarget.dataset.src;
    const imgList = this.data.swiperList;
    const list = imgList.map(item => {
      if (item.type == 'image') {
        return getURL.getImgUrl(item.picUrl)
      }
    })
    wx.previewImage({
      current: getURL.getImgUrl(src), // 当前显示图片
      urls: list // 需要预览的图片列表
    })
  },
  //开始播放视频
  goPlayVideo(e) {
    var that = this;
    var videoplay = wx.createVideoContext('video')
    wx.getNetworkType({ // 获取网络类型
      success: function (res) {
        if (res.networkType != 'wifi') {
          that.setData({
            showNotWifiPaly: true
          })
          setTimeout(function () {
            that.setData({
              showNotWifiPaly: false
            })
          }, 1500)
        }
      }
    })
    videoplay.play()
    that.setData({
      swiperTyle: false,
      PlayTyle: true
    })
  },
  //监听播放完
  palyEndLitten(e) {
    this.setData({
      PlayTyle: false
    })
  },
  // 停止播放
  stopPalyVideo(e) {
    var videoplay = wx.createVideoContext('video')
    videoplay.pause()
  },
  // 点赞
  toThumbsUp() {
    if (this.data.isThumbsUp) {
      // 取消点赞
      const apiUrl = `${foundApi.removeThumbsUp}${this.data.thumbsUpId}`
      app.reqFun.requestJson('DELETE', apiUrl, {}, (response) => {
        if (response.data) {
          const res = response.data
          if (res.success === 1) {
            this.setData({
              thumbsUpNum: this.data.thumbsUpNum - 1,
              isThumbsUp: false,
              thumbsUpId: ''
            })
          } else {
            wx.showToast({
              title: (res.data && res.data.msg) || '网络异常',
              icon: 'none'
            })
          }
        }
      })
    } else {
      // 点赞
      const params = {
        id: this.data.contentId,
        type: 'content',
      }
      app.reqFun.requestJson('GET', foundApi.thumbsUp, params, (response) => {
        if (response.data) {
          const res = response.data
          if (res.data && res.success === 1) {
            this.setData({
              thumbsUpNum: this.data.thumbsUpNum + 1,
              thumbsUpId: res.data,
              isThumbsUp: true
            })
          } else {
            wx.showToast({
              title: (res.data && res.data.msg) || '网络异常',
              icon: 'none'
            })
          }
        }
      })
    }
  },
  // 收藏
  toCollect() {
    if (this.data.isCollection) {
      // 取消收藏
      const collectionId = this.data.collectionId
      app.reqFun.requestJson('GET', foundApi.removeCollection, {
        ids: collectionId
      }, (response) => {
        if (response.data) {
          const res = response.data
          if (res.success === 1) {
            this.setData({
              isCollection: false,
              collectionId: ''
            })
          } else {
            wx.showToast({
              title: (res.data && res.data.msg) || '网络异常',
              icon: 'none'
            })
          }
        }
      })
    } else {
      // 收藏
      const contentId = this.data.contentId
      app.reqFun.requestJson('GET', foundApi.collection, {
        contentId
      }, (response) => {
        if (response.data) {
          const res = response.data
          if (res.success == 1 && res.data) {
            this.setData({
              isCollection: true,
              collectionId: res.data
            })
          } else {
            wx.showToast({
              title: (res.data && res.data.msg) || '网络异常',
              icon: 'none'
            })
          }
        }
      })
    }
  },
  moveHandle() {

  },
  // 打开评论
  openComment() {
    let that = this
    app.getLogin((re)=>{
      if(re){
        // this.setData({
        //   modelPopup: 'comment-pop'
        // })
        wx.showToast({
          title: '功能开发中，敬请期待！',
          icon: 'none'
        })
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
  // 查看相关商品
  viewRelativeGoods() {
    this.setData({
      modelPopup: 'goods-pop'
    })
  },
  //打开分享海报弹窗
  openShareModal: function (e) {
    let that = this
    app.getLogin((re)=>{
      if(re){
        const userId = wx.getStorageSync('loginMsg').userId
        const parms = {
          page: `packagBuy/pages/found/contentDetail/contentDetail`,
          // page:`packageShop/pages/goodsInfo/goodsInfo`,
          scene: JSON.stringify({
            userId: userId,
            id: that.data.contentId
          })
        }
        that.getCavasMainImage()
        // 生成分享二维码
        app.reqFun.requestJson('POST', QRCode, parms, (response) => {
          if (response.data) {
            const res = response.data
            if (res.success == 1 && res.data) {
              that.setData({
                shearImg: `data:image/png;base64,${res.data}`,
                modelPopup: 'shear-pop-download'
              })
              that.saveShareCodeToCashImg(`data:image/png;base64,${res.data}`)
            }
          }
        })
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
  //base64图片转本地缓存图片
  saveShareCodeToCashImg(code) {
    const that = this;
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    const cashImgPath = wx.env.USER_DATA_PATH + '/' + times + '.png';
    //将base64图片写入
    fs.writeFile({
      filePath: cashImgPath,
      data: code.slice(22),
      encoding: 'base64',
      success: function () {
        that.setData({
          canvasQrCode: cashImgPath
        })
      }
    });
  },
   //分享海报
   downloadCanvas:function(e){
    const that=this
    wx.showLoading({
      title: '图片生成中···',
    })
    const contentDetail=that.data.detailData
    const userName=that.data.userInfo.nickname
    const userPhone=that.data.userInfo.phone
    const canvasAvatar=that.data.canvasAvatar
    const canvasMainPic=that.data.canvasMainPic
    const canvasQrCode=that.data.canvasQrCode
    const canvasBottomBg=that.data.canvasBottomBg
    const shareTitle= contentDetail.name
    const shareDesc=contentDetail.contentDesc
    console.log('shareTitle', shareTitle, shareDesc)
    const unit = that.data.screenWidth / 375;

    const ctx= wx.createCanvasContext('share-poster');
    ctx.beginPath() //绘制用户信息区域的背景
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, unit * 300, unit * 62)
    ctx.save()

    const avatorWidth = unit * 42
    const avatorHeight = unit * 42
    const avatarurlX = unit * 10; //绘制的头像在画布上的位置
    const avatarurlY = unit * 10; //绘制的头像在画布上的位置

    ctx.beginPath() //绘制用户头像
    ctx.arc(avatorWidth / 2 + avatarurlX, avatorHeight / 2 + avatarurlY, avatorWidth / 2, 0, Math.PI * 2, false); // 创建一个圆
    ctx.clip() // 从原始画布中剪切圆形
    ctx.drawImage(canvasAvatar, avatarurlX, avatarurlY, avatorWidth, avatorHeight) // 网络图片要通过 getImageInfo / downloadFile 先下载
    ctx.restore()

    ctx.beginPath() //开始绘制用户名称
    ctx.setFillStyle('#333')
    ctx.font = "bold 14px Arial";
    ctx.setFontSize(unit * 14);
    if(userPhone) {
      ctx.fillText(userName,unit * 64,unit * 20)
    } else {
      ctx.fillText(userName,unit * 64,unit * 27)
    }

    if(userPhone) {
      ctx.beginPath()   //开始绘制用户电话
      ctx.setFillStyle('#333')
      ctx.font = "12px Arial";
      ctx.setFontSize(unit * 12);
      ctx.fillText(userPhone,unit * 64,unit * 38)
    }

    // ctx.beginPath()  //绘制标签
    ctx.setFillStyle('#888')
    ctx.font = "12px Arial";
    ctx.setFontSize(unit * 12);
    if(userPhone) {
      ctx.fillText('给您分享这篇文章', unit * 64, unit * 55)
    } else {
      ctx.fillText('给您分享这篇文章', unit * 64, unit * 50)
    }
    
    const mainPicY = unit * 62
    // const mainPicHeight = unit * 148
    const mWidth = that.data.mainPicWidth || 280
    const mHeight = that.data.mainPicHeight || 148
    const mainPicHeight = unit * (280 / mWidth * mHeight)
    // ctx.beginPath()   //绘制主图
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, mainPicY, unit * 300, mainPicHeight)
    ctx.drawImage(canvasMainPic, unit * 10, mainPicY, unit * 280, mainPicHeight)
    ctx.restore()

    const wordAreaY = mainPicY + mainPicHeight
    ctx.beginPath() //开始绘制文字描述部分白色背景图
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, wordAreaY, unit * 300, unit * 200)

    const titleY = wordAreaY + unit * (10 + 14 + 3) // 标题Y轴起始点:10为间距，14 字体高度，3为20的行距减去字体大小14再除以2
    ctx.font = "bold " + (unit * 14) + "px 微软雅黑"; // 设置标题字体大小
    ctx.setFontSize(unit * 14);
    ctx.setFillStyle('#333') // 设置标题字体颜色
    // const titleHeight= this.drawText(ctx, shareTitle, unit * 10, titleY, unit * 280,unit * 40,2,unit) //处理标题文字换行且绘制标题
    let titleHeight = this.drawText(ctx, shareTitle, unit * 10, titleY, unit * 280, unit * 20, unit) //处理标题文字换行且绘制标题

    const descY = titleY + titleHeight + unit * 10 //描述文字Y轴起点：10 间距，12字体大小，5，行距减去字体大小的一半
    // ctx.beginPath()   //开始绘制简介部分
    ctx.font = (unit * 12) + "px 微软雅黑";
    ctx.setFontSize(unit * 12);
    ctx.setFillStyle('#333')
    // this.drawText(ctx, shareDesc, unit * 10, descY,unit * 142, unit * 88,4,unit) //字体换行
    let descHeight = this.drawText(ctx, shareDesc, unit * 10, descY, unit * 142, unit * 22, unit) //字体换行
    // ctx.restore()
    if (descHeight < unit * 88) {
      descHeight = unit * 88 // 文字描述高度最低 88 
    }

    const codeTopTitle = titleY + titleHeight - (14 + 3) * unit // 二维码Y轴起点(位置烤近标题最后一行,)
    const codeImgHeight = unit * 80
    let codeImgY = descY + descHeight - (codeImgHeight + 40 * unit) // 二维码低部与描述文字底部对齐
    if (codeTopTitle > codeImgY) {
      codeImgY = codeTopTitle
    }

    // ctx.beginPath() //绘制二维码
    // ctx.setFillStyle('#ff00ff')
    ctx.drawImage(canvasQrCode, unit * 180, codeImgY, unit * 80, codeImgHeight)
    // ctx.fillRect(unit * 180,codeImgY,unit * 80,codeImgHeight)

    const codeDescY = codeImgY + codeImgHeight + (10 + 3) * unit // 二维码提示文字Y轴起点 ：10字体大小，3 为距离二维码的间距
    ctx.beginPath()
    ctx.font = "10px Arial";
    ctx.setFontSize(unit * 10);
    ctx.setFillStyle('#888')
    ctx.fillText('长按扫码识别', unit * 188, codeDescY)
    // ctx.restore()
    const btBgY = codeImgY + codeImgHeight + (3 * unit)
    // ctx.beginPath() //绘制底部背景
    // ctx.drawImage(canvasBottomBg,0,unit * 342,unit * 300,unit * 68)
    ctx.drawImage(canvasBottomBg, 0, btBgY, unit * 300, unit * 68)
    ctx.restore();
    const canvasHeight = btBgY + (unit * 68)
    this.setData({
      canvasHeight
    })
    setTimeout(() => {
      ctx.draw(true, () => {
        wx.canvasToTempFilePath({ //canvas生成图片
          x: 0,
          y: 0,
          width: unit * 300,
          height: canvasHeight,
          // height: unit * 410,
          // destWidth: unit * 300 * 2,  //*2是为了让图片分辨率更大，显得更清晰
          // destHeight: unit * 410 * 2,
          canvasId: 'share-poster',
          fileType: 'png',
          success(res) {
            wx.saveImageToPhotosAlbum({ //保存图片到相册
              filePath: res.tempFilePath,
              success: function (e) {
                wx.hideLoading({})
                wx.showToast({
                  title: '保存图片成功',
                  duration: 3000
                })
                that.setData({
                  modelPopup: ''
                })
              },
              fail: function (e) {
                wx.hideLoading({})
                wx.showModal({
                  title: '保存失败',
                  content: '保存图片失败,请点击右上角按钮-设置-开启授权',
                  showCancel: false,
                })
              }
            })
          },
          fail(res) {
            console.log(res)
          }
        })
      })
    }, 1000)

  },
  /*
   * cavas 文字换行
   * @params {String} ctx canvas组件的绘图上下文
   * @params {String} str 文字字符串内容
   * @params {Number} leftWidth 距离x轴距离
   * @params {Number} initHeight 文字Y轴的起始点
   * @params {Number} canvasWidth 文字画布区域的宽度
   * @params {Number} lineHeight 行高
   * @params {Number} line 行数
   */
  drawText(ctx, str, leftWidth, initHeight, canvasWidth, lineHeight, unit) {
    let lineWidth = 0; // 行宽
    let lastSubStrIndex = 0; // 每次开始截取的字符串的索引
    let titleHeight = lineHeight // 文字区域高度
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width + 1 * unit; //获取一个字符的宽度，加1px空格        
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分文字           
        initHeight += lineHeight; //lineHeight行高          
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += lineHeight
      }
      if (i == str.length - 1) { //绘制剩余部分                
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离        
    // titleHeight = titleHeight + 10 * unit;     
    return titleHeight
  },
  onCloseModel(e) { //关闭弹窗
    this.setData({
      modelPopup: ''
    })
  },
  inputCommenContent(e) {
    const content = e.detail.value
    this.setData({
      commentContent: content
    })
  },
  //发表评论
  submitComment(e) {
    if (this.data.commentSubmit) return
    const content = e.detail.value.comment_content
    if (!content || content.trim().length == 0) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      })
      return
    }

    this.setData({
      commentSubmit: true
    })
    app.reqFun.requestForm('POST', foundApi.commentSave, {
      content
    }, (response) => {
      this.setData({
        commentSubmit: false,
        commentContent: ''
      })
      if (response.data) {
        const res = response.data
        if (res.success == 1) {
          this.getCommentList() // 发表评论成功后刷新评论列表
          this.setData({
            commentSubmit: false,
            commentContent: ''
          })
        } else {
          wx.showToast({
            title: (res.data && res.data.msg) || '该功能暂不可使用',
            icon: 'none'
          })
          this.setData({
            commentSubmit: false
          })
        }
      }
    })
  },
  //展开合伙人信息
  showPartnerAll: function () {
    let isShowPartnerAll;
    if (this.data.isShowPartnerAll == 1) {
      isShowPartnerAll = 0;
    } else {
      isShowPartnerAll = 1;
    }
    this.setData({
      isShowPartnerAll: isShowPartnerAll,
    })
  },
  //展示合伙人二维码
  partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    console.log("3253456678dsgudkdkgfksfvkjdsvbjkdsvbvkj")
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  }
})